import 'package:flutter/material.dart';
import '../../api/notification_service.dart';
import '../../models/notification.dart' as app_notification;
import '../../utils/date_util.dart';
import '../../config/app_theme.dart';

class NotificationScreen extends StatefulWidget {
  @override
  _NotificationScreenState createState() => _NotificationScreenState();
}

class _NotificationScreenState extends State<NotificationScreen> with SingleTickerProviderStateMixin {
  final NotificationService _notificationService = NotificationService();
  late TabController _tabController;
  List<app_notification.Notification> _allNotifications = [];
  bool _isLoading = true;
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
    _loadNotifications();
  }
  
  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
  
  Future<void> _loadNotifications() async {
    setState(() {
      _isLoading = true;
    });
    
    try {
      // 模拟获取当前用户ID
      final String userId = 'current_user';
      final notifications = await _notificationService.getNotifications(userId);
      
      setState(() {
        _allNotifications = notifications;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      print('Error loading notifications: $e');
    }
  }
  
  Future<void> _markAsRead(String notificationId) async {
    try {
      final success = await _notificationService.markAsRead(notificationId);
      
      if (success) {
        setState(() {
          _allNotifications = _allNotifications.map((notification) {
            if (notification.id == notificationId) {
              return notification.markAsRead();
            }
            return notification;
          }).toList();
        });
      }
    } catch (e) {
      print('Error marking notification as read: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('标记通知已读失败，请稍后再试'))
      );
    }
  }
  
  Future<void> _markAllAsRead() async {
    try {
      final success = await _notificationService.markAllAsRead('current_user');
      
      if (success) {
        setState(() {
          _allNotifications = _allNotifications.map((notification) => notification.markAsRead()).toList();
        });
        
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已将所有通知标记为已读'))
        );
      }
    } catch (e) {
      print('Error marking all notifications as read: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('标记所有通知已读失败，请稍后再试'))
      );
    }
  }
  
  Future<void> _deleteNotification(String notificationId) async {
    try {
      final success = await _notificationService.deleteNotification(notificationId);
      
      if (success) {
        setState(() {
          _allNotifications.removeWhere((notification) => notification.id == notificationId);
        });
        
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('通知已删除'))
        );
      }
    } catch (e) {
      print('Error deleting notification: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('删除通知失败，请稍后再试'))
      );
    }
  }
  
  List<app_notification.Notification> _getFilteredNotifications(app_notification.NotificationType? type) {
    if (type == null) {
      return _allNotifications;
    }
    return _allNotifications.where((notification) => notification.type == type).toList();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('消息通知'),
        actions: [
          if (!_isLoading && _allNotifications.isNotEmpty)
            IconButton(
              icon: Icon(Icons.done_all),
              onPressed: _markAllAsRead,
              tooltip: '全部标为已读',
            ),
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: [
            Tab(text: '全部'),
            Tab(text: '点赞'),
            Tab(text: '评论'),
            Tab(text: '系统'),
          ],
        ),
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : _allNotifications.isEmpty
              ? _buildEmptyView()
              : TabBarView(
                  controller: _tabController,
                  children: [
                    _buildNotificationList(null),
                    _buildNotificationList(app_notification.NotificationType.like),
                    _buildNotificationList(app_notification.NotificationType.comment),
                    _buildNotificationList(app_notification.NotificationType.system),
                  ],
                ),
    );
  }
  
  Widget _buildEmptyView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.notifications_off,
            size: 64,
            color: Colors.grey[400],
          ),
          SizedBox(height: 16),
          Text(
            '暂无消息通知',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
          SizedBox(height: 8),
          Text(
            '与其他用户互动后，你会收到相关通知',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildNotificationList(app_notification.NotificationType? type) {
    final filteredNotifications = _getFilteredNotifications(type);
    
    if (filteredNotifications.isEmpty) {
      return Center(
        child: Text(
          '暂无${type == app_notification.NotificationType.like ? '点赞' : type == app_notification.NotificationType.comment ? '评论' : type == app_notification.NotificationType.system ? '系统' : ''}通知',
          style: TextStyle(color: Colors.grey[600]),
        ),
      );
    }
    
    return RefreshIndicator(
      onRefresh: _loadNotifications,
      child: ListView.builder(
        itemCount: filteredNotifications.length,
        itemBuilder: (context, index) {
          final notification = filteredNotifications[index];
          return _buildNotificationItem(notification);
        },
      ),
    );
  }
  
  Widget _buildNotificationItem(app_notification.Notification notification) {
    return Dismissible(
      key: Key(notification.id),
      background: Container(
        color: Colors.red,
        alignment: Alignment.centerRight,
        padding: EdgeInsets.only(right: 16.0),
        child: Icon(
          Icons.delete,
          color: Colors.white,
        ),
      ),
      direction: DismissDirection.endToStart,
      onDismissed: (direction) {
        _deleteNotification(notification.id);
      },
      child: InkWell(
        onTap: () {
          if (!notification.isRead) {
            _markAsRead(notification.id);
          }
          // TODO: 导航到相关内容
        },
        child: Container(
          color: notification.isRead ? null : Colors.blue.withOpacity(0.05),
          child: ListTile(
            leading: Stack(
              children: [
                CircleAvatar(
                  backgroundColor: notification.getNotificationColor().withOpacity(0.2),
                  child: Icon(
                    notification.getNotificationIcon(),
                    color: notification.getNotificationColor(),
                    size: 20,
                  ),
                ),
                if (notification.imageUrl != null)
                  Positioned(
                    bottom: 0,
                    right: 0,
                    child: CircleAvatar(
                      radius: 8,
                      backgroundImage: NetworkImage(notification.imageUrl!),
                    ),
                  ),
              ],
            ),
            title: Text(
              notification.content,
              style: TextStyle(
                fontWeight: notification.isRead ? FontWeight.normal : FontWeight.bold,
              ),
            ),
            subtitle: Text(
              DateUtil.formatTimeAgo(notification.createdAt),
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[600],
              ),
            ),
            trailing: !notification.isRead
                ? GestureDetector(
                    onTap: () => _markAsRead(notification.id),
                    child: Container(
                      width: 12,
                      height: 12,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: AppTheme.primaryColor,
                      ),
                    ),
                  )
                : null,
          ),
        ),
      ),
    );
  }
} 